<style>
h1 {font-size:20;} h2 {font-size:16;} h3 {font-size:12;} h4 {font-size:8;} h5 {font-size:4;} h6 {font-size:2;}
</style>
<pre>
<?php
/*
 TODO : Add work breaks and parameterise work times
      : Sort allocations of work skills by scarcity
      : Write the results away to the work table
      : Need to be able to start work tasks so that they can't be overwritten
*/
require_once("include.php");
global $workers;
global $employees;
global $skills;
global $order;
// Who can make stuff
$sql = ("select itemid,name from employee where itemid in (select employeeid from skillmatch)");
$employees = sqlreadkeyarray($sql);
// What can they make
$temp = sqlreadarray("select processid,employeeid from skillmatch");
$skills = array();
foreach ($temp as $tempitem) {
 $processid = $tempitem[0]; $employeeid = $tempitem[1];
 $skills[$processid][] = $employeeid;
}
// What needs to be made
$work = sqlreadarray("select * from sorderline");
foreach($work as $line) {
 $prod = $line[5];
 $order = $line[0]."-".$line[1];
 drill($prod,1,0);
}
print_r($employees);;

function drill($productid,$l,$est) {
 global $employees;
 global $skills;
 global $work;
 global $order;

 $productitem = freaditem("product",$productid);
 $sql = "select subproduct from productbuilds where itemid='$productid'";
 $subs = sqlreadarray($sql) ;
 $eft = 0;
 if ($subs !== "") {
  foreach ($subs as $item) {
   
   $thiseft = drill($item[0],$l+1,$est);
   if ($thiseft > $eft) {
	  $eft = $thiseft;
	 }
  }
  
 } else {
 }
 $skill = $productitem[18];
 $duration = $productitem[23];
 if ($skill) {
    // Find who can do this work 
    $employeeid = $skills[$skill][0];

/*******************************/

    
    // Find a gap of duration length
    $subfrm = max(strtotime("2009-12-06 09:00:00"),$eft);
    $frm = $subfrm;
    if (isset($employees[$employeeid][2])) {
     $subarray = $employees[$employeeid][2];
     foreach ($subarray as $fromdate=>$dateitem) {
      if (strtotime($fromdate)-$frm > $duration*60) {
       break ;
      } else {
       $frm = max($subfrm,strtotime($dateitem[3]));
      }
     }     
    }
    
    // Add item to array
		$newitem = array($productid,$skill,$order,date("Y-m-d H:i:s",$frm+$duration*60));		
    $employees[$employeeid][2][date("Y-m-d H:i:s",$frm)] = $newitem;
    // Sort array by start time
    ksort($employees[$employeeid][2]);
    
    $eft = $frm+$duration*60 ;

/*******************************/

 } else {
 }
 
 return $eft;
  
}

?>